package com.yanti.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.yanti.common.constant.RedisConstants;
import com.yanti.domain.ResponseResult;
import com.yanti.domain.dto.SendVerificationCodeReqDTO;
import com.yanti.domain.enums.AppHttpCodeEnum;
import com.yanti.service.VerificationCodeService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class VerificationCodeServiceImpl implements VerificationCodeService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 发送验证码
     * @param sendVerificationCodeReqDTO 发送验证码请求DTO
     * @return 响应结果
     */
    @Override
    public ResponseResult<?> sendVerificationCode(SendVerificationCodeReqDTO sendVerificationCodeReqDTO) {
        // 获取手机号
        String phone = sendVerificationCodeReqDTO.getPhone();
        // 根据手机号构建Redis key
        String key = RedisConstants.buildVerificationCodeKey(phone);
        // 判断key是否存在
        if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) {
            // 如果存在，提示用户稍后再试
            return ResponseResult.errorResult(AppHttpCodeEnum.VERIFICATION_CODE_SEND_FREQUENTLY);
        }
        // 如果不存在，使用hutool生成验证码并发送
        String verificationCode = RandomUtil.randomNumbers(6);
        // todo 调用第三方短信服务发送验证码
        log.info("==> 手机号: {}, 已发送验证码：【{}】", phone, verificationCode);
        // 保存验证码到Redis中，过期时间为3分钟
        redisTemplate.opsForValue().set(key, verificationCode,3, TimeUnit.MINUTES);
        // 返回成功响应
        return ResponseResult.okResult(verificationCode);
    }
}
